<template>
  <view class="page-container">
    <uni-card 
      title="水滴轮廓检测" 
      :is-full="true"
      :is-shadow="false"
      class="full-card"
    >
      <!-- 页面顶部导航和标题 -->
      <view class="page-header">
        <text class="page-subtitle">精确测量接触角的专业工具</text>
      </view>
      
      <!-- 服务器配置 -->
      <!-- <view class="server-config section-card">
        <uni-section title="服务器配置" type="line">
          <view class="section-content">
            <view class="server-input-group">
              <text class="server-label">服务器地址:</text>
              <uni-easyinput v-model="serverConfig.host" placeholder="输入服务器IP地址" class="server-input" />
            </view>
            <view class="server-input-group">
              <text class="server-label">端口:</text>
              <uni-easyinput v-model="serverConfig.port" type="number" placeholder="输入端口号" class="server-input" />
            </view>
            <view class="server-input-group">
              <text class="server-label">路径前缀:</text>
              <uni-easyinput v-model="serverConfig.prefix" placeholder="例如: /Droppy" class="server-input" />
            </view>
            <button @click="saveServerConfig" class="server-save-btn">保存配置</button>
          </view>
        </uni-section>
      </view> -->
      
      <!-- 图片上传区域 -->
      <view class="image-section section-card">
        <uni-section title="图像分析" type="line">
          <view class="section-content">
            <view class="image-upload" @click="chooseImage">
              <image v-if="imageSrc" :src="imageSrc" mode="aspectFit"></image>
              <view v-else class="upload-placeholder">
                <uni-icons type="camera-filled" size="50" color="#4c84ff"></uni-icons>
                <text>点击选择图片</text>
              </view>
            </view>
            
            <view class="detection-results" v-if="ellipseResult">
              <view class="detection-overlay">
                <!-- 这里可以添加椭圆轮廓的可视化显示 -->
              </view>
            </view>
          </view>
        </uni-section>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-container">
        <view 
          class="action-button detect-button" 
          :class="{'disabled': !hasImage}" 
          @click="hasImage && detectEllipse()"
        >
          <uni-icons type="search" size="16" color="#fff"></uni-icons>
          <text class="button-text">检测轮廓</text>
        </view>
        
        <view 
          class="action-button calculate-button" 
          :class="{'disabled': !hasEllipse}" 
          @click="hasEllipse && calculateAngle()"
        >
          <uni-icons type="refresh" size="16" color="#fff"></uni-icons>
          <text class="button-text">计算接触角</text>
        </view>
        
        <view 
          class="action-button save-button" 
          :class="{'disabled': !angleResult}" 
          @click="angleResult && saveResult()"
        >
          <uni-icons type="save" size="16" color="#fff"></uni-icons>
          <text class="button-text">保存结果</text>
        </view>
      </view>
      
      <!-- 结果展示 -->
      <view class="results-container">
        <!-- 椭圆检测结果 -->
        <view class="result-section section-card" v-if="ellipseResult">
          <uni-section title="检测结果" type="line">
            <view class="section-content result-content">
              <view class="result-grid">
                <view class="result-item">
                  <view class="result-label">椭圆中心</view>
                  <view class="result-value">
                    ({{ellipseResult[0][0].toFixed(2)}}, {{ellipseResult[0][1].toFixed(2)}})
                  </view>
                </view>
                
                <view class="result-item">
                  <view class="result-label">长轴/短轴</view>
                  <view class="result-value">
                    {{ellipseResult[1][0].toFixed(2)}} / {{ellipseResult[1][1].toFixed(2)}}
                  </view>
                </view>
                
                <view class="result-item">
                  <view class="result-label">旋转角度</view>
                  <view class="result-value">
                    {{ellipseResult[2].toFixed(2)}} <text class="result-unit">°</text>
                  </view>
                </view>
              </view>
            </view>
          </uni-section>
        </view>
        
        <!-- 接触角结果 -->
        <view class="result-section section-card" v-if="angleResult">
          <uni-section title="接触角" type="line">
            <view class="section-content result-content">
              <view class="result-grid">
                <view class="result-item" v-for="(angle, index) in angleResult" :key="index">
                  <view class="result-label">接触角 {{index + 1}}</view>
                  <view class="result-value">
                    {{angle.toFixed(2)}} <text class="result-unit">°</text>
                  </view>
                </view>
              </view>
            </view>
          </uni-section>
        </view>
      </view>
    </uni-card>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 服务器配置（固定值，不需要保存到本地）
const apiBaseUrl = "http://47.97.2.25:7020/Droppy";
// const apiBaseUrl = "http://47.97.2.25:7020/Droppy";
// http://s.wangchenyang.info/droppy/Droppy

// 状态管理
const imageSrc = ref('');
const ellipseResult = ref(null);
const angleResult = ref(null);

// 计算属性
const hasImage = computed(() => !!imageSrc.value);
const hasEllipse = computed(() => !!ellipseResult.value);

// 页面加载时检查是否有传入的图片
onMounted(() => {
  // 检查是否有传入的图片路径
  const analyzedImagePath = uni.getStorageSync('analyzedImagePath');
  if (analyzedImagePath) {
    imageSrc.value = analyzedImagePath;
    // 清除存储，避免影响下次使用
    uni.removeStorageSync('analyzedImagePath');
  }
});

// 当前项目ID
const currentProjectId = ref('');

// 页面加载时获取当前项目ID
onMounted(() => {
  const projectId = uni.getStorageSync('currentProjectId');
  if (projectId) {
    currentProjectId.value = projectId;
    // 清除存储，避免影响下次使用
    uni.removeStorageSync('currentProjectId');
  }
});

// 封装的请求方法
const apiRequest = async (endpoint, data) => {
  try {
    const url = `${apiBaseUrl}${endpoint}`;
    console.log('请求URL:', url);
    
    const res = await uni.request({
      url: url,
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: data,
      timeout: 30000 // 30秒超时
    });
    
    console.log('响应状态:', res.statusCode);
    
    if (res.statusCode === 200) {
      return res.data;
    } else {
      throw new Error(res.data?.message || `HTTP错误: ${res.statusCode}`);
    }
  } catch (e) {
    console.error(`API请求失败 (${endpoint}):`, e);
    
    // 提供更明确的错误信息
    if (e.errMsg && e.errMsg.includes('fail')) {
      if (e.errMsg.includes('timeout')) {
        throw new Error('请求超时，请检查服务器是否正常运行');
      } else if (e.errMsg.includes('refused')) {
        throw new Error('连接被拒绝，请检查网络连接');
      } else {
        throw new Error(`网络错误: ${e.errMsg}`);
      }
    }
    
    throw e;
  }
};

// 工具方法
const pathToBase64 = async (path) => {
  return new Promise((resolve, reject) => {
    uni.getFileSystemManager().readFile({
      filePath: path,
      encoding: 'base64',
      success: res => {
        let base64Str = res.data;
        while (base64Str.length % 4) {
          base64Str += '=';
        }
        resolve(base64Str);
      },
      fail: err => reject(err)
    });
  });
};

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      extension: ['png', 'jpg', 'jpeg']
    });
    
    imageSrc.value = res.tempFilePaths[0];
    ellipseResult.value = null;
    angleResult.value = null;
  } catch (e) {
    console.error('选择图片失败:', e);
    uni.showToast({
      title: '选择图片失败',
      icon: 'none'
    });
  }
};

// 检测椭圆
const detectEllipse = async () => {
  if (!imageSrc.value) {
    uni.showToast({
      title: '请先选择图片',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: '检测中...'
    });
    
    const base64Image = await pathToBase64(imageSrc.value);
    
    const data = await apiRequest('/getEllipse', {
      imageSrc: base64Image
    });
    
    uni.hideLoading();
    
    if (data) {
      ellipseResult.value = data;
      uni.showToast({
        title: '检测成功',
        icon: 'success'
      });
    } else {
      throw new Error('服务器返回空数据');
    }
  } catch (e) {
    uni.hideLoading();
    console.error('检测失败:', e);
    uni.showToast({
      title: e.message || '检测失败',
      icon: 'none'
    });
  }
};

// 计算接触角
const calculateAngle = async () => {
  if (!ellipseResult.value) {
    uni.showToast({
      title: '请先检测轮廓',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: '计算中...'
    });
    
    // 构建基准线参数
    const baseLineParams = {
      start: { x: 0, y: ellipseResult.value[0][1] },
      end: { x: ellipseResult.value[1][0] * 2, y: ellipseResult.value[0][1] }
    };
    
    // 计算直线参数 [vx, vy, x0, y0]
    const dx = baseLineParams.end.x - baseLineParams.start.x;
    const dy = baseLineParams.end.y - baseLineParams.start.y;
    const length = Math.sqrt(dx * dx + dy * dy);
    
    const requestData = {
      ellipse: [
        ellipseResult.value[0][0], // 中心点x
        ellipseResult.value[0][1], // 中心点y
        ellipseResult.value[1][0], // 长轴
        ellipseResult.value[1][1], // 短轴
        ellipseResult.value[2]     // 旋转角度
      ],
      line: [
        dx / length,  // vx - 单位向量x分量
        dy / length,  // vy - 单位向量y分量
        baseLineParams.start.x,  // x0 - 起点x坐标
        baseLineParams.start.y   // y0 - 起点y坐标
      ]
    };
    
    const data = await apiRequest('/getAngle', requestData);
    
    uni.hideLoading();
    
    if (data) {
      angleResult.value = data;
      
      // 保存分析结果到当前项目
      // saveAnalysisResult();
      
      uni.showToast({
        title: '计算成功',
        icon: 'success'
      });
    } else {
      throw new Error('服务器返回空数据');
    }
  } catch (e) {
    uni.hideLoading();
    console.error('计算失败:', e);
    uni.showToast({
      title: e.message || '计算失败',
      icon: 'none'
    });
  }
};

// 保存分析结果到项目
const saveAnalysisResult = () => {
  if (currentProjectId.value && ellipseResult.value && angleResult.value) {
    // 构建分析结果数据
    const resultData = {
      ellipse: {
        center_x: ellipseResult.value[0][0],
        center_y: ellipseResult.value[0][1],
        major_axis: ellipseResult.value[1][0],
        minor_axis: ellipseResult.value[1][1],
        rotation: ellipseResult.value[2]
      },
      angles: angleResult.value
    };
    
    // 发送事件通知项目页面更新数据
    uni.$emit('analysisComplete', {
      projectId: currentProjectId.value,
      type: '轮廓接触角分析',
      result: resultData
    });
    
    uni.showToast({
      title: '已保存到项目',
      icon: 'success'
    });
  }
};

// 保存结果
const saveResult = () => {
  if (currentProjectId.value && ellipseResult.value && angleResult.value) {
    // 构建分析结果数据
    const resultData = {
      ellipse: {
        center_x: ellipseResult.value[0][0],
        center_y: ellipseResult.value[0][1],
        major_axis: ellipseResult.value[1][0],
        minor_axis: ellipseResult.value[1][1],
        rotation: ellipseResult.value[2]
      },
      angles: angleResult.value
    };
    
    // 发送事件通知项目页面更新数据
    uni.$emit('analysisComplete', {
      projectId: currentProjectId.value,
      type: '轮廓接触角分析',
      result: resultData
    });
    
    // 显示保存成功提示
    uni.showToast({
      title: '已保存到项目',
      icon: 'success'
    });
    
    // 延迟返回到项目页面
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } else {
    if (!currentProjectId.value) {
      uni.showToast({
        title: '未找到项目信息',
        icon: 'none'
      });
    } else if (!ellipseResult.value || !angleResult.value) {
      uni.showToast({
        title: '请先完成分析',
        icon: 'none'
      });
    }
  }
};
</script>

<style lang="scss">
// 主题色变量
$primary-color: #4c84ff;
$secondary-color: #00b8a9;
$light-primary: #eef4ff;
$dark-primary: #3a67cc;
$background-color: #f8f9fc;
$card-bg-color: #ffffff;
$text-color: #333333;
$text-secondary: #666666;
$text-muted: #999999;
$border-color: #e8e8f0;
$success-color: #52c41a;
$warning-color: #faad14;
$error-color: #f5222d;

.page-container {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 30px;
  
  .page-header {
    margin-bottom: 25px;
    
    .page-subtitle {
      font-size: 14px;
      color: $text-secondary;
      letter-spacing: 0.5px;
      display: block;
    }
  }
  
  .full-card {
    margin: 0;
    padding: 0;
    
    :deep(.uni-card) {
      margin: 0;
      padding: 0;
      border-radius: 0;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      
      .uni-card__header {
        padding: 18px 24px;
        border-bottom: 1px solid $border-color;
        background-color: $card-bg-color;
        
        .uni-card__header-title {
          font-size: 20px;
          font-weight: 600;
          color: $text-color;
        }
      }
      
      .uni-card__content {
        padding: 24px;
      }
    }
  }
  
  .section-card {
    background-color: $card-bg-color;
    border-radius: 8px;
    margin-bottom: 20px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    :deep(.uni-section) {
      .uni-section__head {
        padding: 12px 16px;
        
        .uni-section__content {
          .uni-section__content-title {
            font-size: 16px;
            font-weight: 600;
            color: $text-color;
          }
        }
      }
    }
    
    .section-content {
      padding: 16px;
    }
  }
  
  .image-section {
    .image-upload {
      width: 100%;
      height: 300px;
      border: 2px dashed lighten($primary-color, 30%);
      border-radius: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      background-color: rgba($primary-color, 0.02);
      transition: all 0.3s ease;
      
      &:hover {
        border-color: $primary-color;
        background-color: rgba($primary-color, 0.05);
      }
      
      image {
        max-width: 100%;
        max-height: 100%;
        border-radius: 4px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      }
      
      .upload-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        color: lighten($primary-color, 10%);
        
        text {
          margin-top: 12px;
          font-size: 15px;
        }
      }
    }
  }
  
  .action-container {
    display: flex;
    justify-content: center;
    gap: 20rpx;
    margin: 24px 0;
    
    .action-button {
      border-radius: 40rpx;
      height: 80rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      flex: 1;
      cursor: pointer;
      
      &.disabled {
        opacity: 0.6;
        box-shadow: none !important;
      }
      
      .button-text {
        margin-left: 10rpx;
        white-space: nowrap;
        color: #fff;
      }
      
      &.detect-button {
        background: linear-gradient(to right, #4080ff, #4a66ff);
        box-shadow: 0 4rpx 12rpx rgba($primary-color, 0.3);
        
        &:active:not(.disabled) {
          background: linear-gradient(to right, #3060d0, #3a46d0);
          transform: translateY(2rpx);
        }
      }
      
      &.calculate-button {
        background: linear-gradient(to right, #00c6ab, #00d6b9);
        box-shadow: 0 4rpx 12rpx rgba($secondary-color, 0.3);
        
        &:active:not(.disabled) {
          background: linear-gradient(to right, #00a68b, #00b699);
          transform: translateY(2rpx);
        }
      }
      
      &.save-button {
        background: linear-gradient(to right, #50c122, #60d132);
        box-shadow: 0 4rpx 12rpx rgba($success-color, 0.3);
        
        &:active:not(.disabled) {
          background: linear-gradient(to right, #40b112, #50c122);
          transform: translateY(2rpx);
        }
      }
    }
  }
  
  .results-container {
    margin-top: 20px;
  }
  
  .result-section {
    .result-content {
      padding: 16px;
      
      .result-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 20px;
        
        .result-item {
          background-color: $light-primary;
          padding: 16px;
          border-radius: 8px;
          border-left: 4px solid $primary-color;
          
          .result-label {
            font-size: 14px;
            color: $text-secondary;
            margin-bottom: 8px;
          }
          
          .result-value {
            font-size: 22px;
            font-weight: 600;
            color: $text-color;
            
            .result-unit {
              font-size: 14px;
              color: $text-secondary;
              font-weight: normal;
              margin-left: 4px;
            }
          }
        }
      }
    }
  }
}

// 添加服务器配置样式
.server-config {
  margin-bottom: 20px;
  
  .section-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .server-input-group {
    display: flex;
    align-items: center;
    
    .server-label {
      width: 100px;
      font-size: 14px;
      color: $text-secondary;
    }
    
    .server-input {
      flex: 1;
    }
  }
  
  .server-save-btn {
    margin-top: 10px;
    background-color: $primary-color;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    font-size: 14px;
    align-self: flex-end;
  }
}
</style> 